package com.baidu.manager.modules.api.utils;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;


/**
 * @Author: jql
 * @description: TODO(jwt工具类)
 * @Date: Created by 16:17 2018/6/14
 */
@ConfigurationProperties(prefix = "sys.jwt")
@Component
public class JwtUtils {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private String secret;
    private long expire;
    private String header;

    public String generateToke(long userId){
        Date nowDate = new Date();
        //过期时间
        Date expireDate = new Date(nowDate.getTime() + expire * 1000);

        return Jwts.builder()
                .setHeaderParam("typ","JWT")
                .setSubject(userId+"")
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    public Claims getClaimByToke(String token){

       try{
           return Jwts.parser()
                   .setSigningKey(secret)
                   .parseClaimsJws(token)
                   .getBody();
       }catch (Exception e){
           logger.error("validate is token error", e.toString());
           return null;
       }
    }

    public boolean isTokenExpired(Date expiration) {
        return expiration.before(new Date());
    }

    public String getSecret() {
        return secret;
    }

    public void setSecret(String secret){
        this.secret = secret;
    }

    public long getExpire(){
        return expire;
    }

    public void setExpire(long expire){
        this.expire = expire;
    }

    public String getHeader(){
        return header;
    }

    public void setHeader(String header) {
        this.header = header;
    }
}
